package yun.web.enjoy.template.ext.directive;

import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.core.io.resource.FileResource;
import cn.hutool.core.io.resource.UrlResource;
import cn.hutool.core.util.ReflectUtil;
import yun.web.enjoy.template.Directive;
import yun.web.enjoy.template.Env;
import yun.web.enjoy.template.expr.ast.Expr;
import yun.web.enjoy.template.io.FastStringWriter;
import yun.web.enjoy.template.io.Writer;
import yun.web.enjoy.template.stat.Scope;

public class FileToStrDirective extends Directive {
    @Override
    public void exec(Env env, Scope scope, Writer writer) {

        //获取指令之前有多少空格

        FastStringWriter fast_string_writer = (FastStringWriter) ReflectUtil.getFieldValue(writer, "out");
        StringBuilder buffer = fast_string_writer.getBuffer();

        // 请注意此处的换行符是 \n 不是\r\n
        int last_index_of = buffer.lastIndexOf("\n");
        String substring = buffer.substring(last_index_of + 1);

        Expr[] directory_params = exprList.getExprArray();
        String file_path = directory_params[0].toString();


        UrlResource resource;
        // 本地文件
        if (file_path.startsWith("file:")) {
            resource = new FileResource(file_path.replace("file:", ""));
        }
        // classpath
        else {
            resource = new ClassPathResource(file_path.replace("classpath:", ""));
        }
        String string = resource.readUtf8Str();


        String[] split = string.split("\r\n");

        if (split.length == 1) {
            split = string.split("\n");
        }

        for (String str : split) {
            write(writer, "\r\n");
            write(writer, substring);
            write(writer, str);
        }
    }

}
